<template>
  <div class="info-config-container">
    <NormalForm pageTitle="客户信息授权配置" :operateForm="queryForm" :formList="formList" :enumOpt="enumOpt" @handleQuery="handleQuery" @handleReset="handleReset" />
    <div class="g-card" style="padding: 0 20px 20px 20px">
      <div class="right-btn" style="margin-right: 0">
        <el-button type="primary" icon="el-icon-s-tools" @click="handleLevelConfig" v-hasPermi="['system:config:add']">授权等级配置</el-button>
      </div>
      <el-table v-loading="loading" :data="infoList" row-key="menuId">
        <el-table-column label="序号" type="index" align="center" min-width="50" />
        <el-table-column label="字段编码" align="center" :show-overflow-tooltip="true" min-width="120">
          <template slot-scope="{ row }">
            <el-button type="text" @click="handleFieldDetail(row)">{{ row.fieldCode }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="字段名称" prop="fieldName" align="center" :show-overflow-tooltip="true" min-width="120" />
        <el-table-column label="信息等级" align="center" min-width="100">
          <template slot-scope="{ row }">
            <div>{{ levelOpt[row.level] }}</div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center" min-width="140" />
        <el-table-column label="更新时间" prop="updateTime" align="center" min-width="140" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="120">
          <template slot-scope="{ row }">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditField(row)" v-hasPermi="['system:config:edit']" :disabled="!row.level" :style="{color: row.level ? '#082aff !important' : '#606266 !important'}">修改</el-button>
            <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelField(row)" v-hasPermi="['system:config:del']">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></NormalPagination>
    </div>
    <!-- 授权等级配置 -->
    <el-dialog title="授权等级配置" :visible.sync="configVisible" width="720px" append-to-body :close-on-click-modal="false" :show-close="false">
      <div class="my-transfer-dialog">
        <el-form ref="configForm" :model="configForm">
          <!-- <el-tag type="warning" class="special-tip">为了保证同一字段信息只会授权一个等级，客户信息等级单次配置其字段信息授权！</el-tag> -->
          <el-form-item prop="level" style="padding: 0;">
            <div class="my-transfer" style="margin-top: 0;">
              <div class="transfer-icon"></div>
              <div class="transfer-title">客户信息等级</div>
            </div>
            <el-select v-model="configForm.level" placeholder="请选择客户信息等级" @change="handleLevelConfig" style="width: 320px;">
              <el-option v-for="item in enumOpt.levelList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
            </el-select>
          </el-form-item>
          <div class="my-transfer">
            <div class="transfer-icon"></div>
            <div class="transfer-title">客户信息等级授权配置</div>
          </div>
          <!-- filterable -->
          <el-transfer
            v-model="configForm.fieldCodeList"
            :data="configList"
            :left-default-checked="leftData"
            :right-default-checked="rightData"
            :titles="['未分配', '已分配']"
            :format="{ noChecked: '${total}', hasChecked: '${checked}/${total}'}"
            @change="handleChange"
            style="display: flex;justify-content: space-between;align-items: center;">
            <!-- style="text-align: left; display: inline-block;" -->
            <span slot-scope="{ option }">{{ option.key }}：{{ option.label }}</span>
          </el-transfer>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-loading="saveLoading" @click="configSubmit">确 定</el-button>
        <el-button @click="configCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改框 -->
    <el-dialog :title="title" :visible.sync="updateVisible" width="620px" append-to-body :close-on-click-modal="false" :show-close="false">
      <el-form class="update-form" ref="updateForm" :model="updateForm" :rules="updateRules" label-width="120px" :hide-required-asterisk="true">
        <el-form-item prop="level">
          <div slot="label" class="normal-label">
            <span v-if="operateFlag !== 'DETAIL'">*</span>客户信息等级：
          </div>
          <div v-if="operateFlag == 'DETAIL'">{{ updateForm.level ? levelOpt[updateForm.level] : '暂未配置' }}</div>
          <el-input v-else v-model="levelOpt[updateForm.level]" disabled style="width: 360px;"></el-input>
        </el-form-item>
        <el-form-item prop="fieldCode">
          <div slot="label" class="normal-label">
            <span v-if="operateFlag !== 'DETAIL'">*</span>字段编码：
          </div>
          <div v-if="operateFlag == 'DETAIL'">{{ updateForm.fieldCode }}</div>
          <el-input v-else v-model="updateForm.fieldCode" disabled style="width: 360px;"></el-input>
        </el-form-item>
        <el-form-item prop="fieldName">
          <div slot="label" class="normal-label">
            <span v-if="operateFlag !== 'DETAIL'">*</span>字段名称：
          </div>
          <div v-if="operateFlag == 'DETAIL'">{{ updateForm.fieldName }}</div>
          <el-input v-else v-model="updateForm.fieldName" placeholder="请输入字段名称" style="width: 360px;"></el-input>
        </el-form-item>
        <el-form-item prop="enterType">
          <div slot="label" class="normal-label">
            <span v-if="operateFlag !== 'DETAIL'">*</span>录入类型：
          </div>
          <div v-if="operateFlag == 'DETAIL'">{{ updateForm.enterType }}</div>
          <el-select v-else v-model="updateForm.enterType" placeholder="请选择录入类型" @change="enterTypeChange" style="width: 360px;">
            <el-option v-for="item in enumOpt.enterTypeList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="['INPUT'].includes(updateForm.enterType)" prop="inputType">
          <div slot="label" class="normal-label">
            <span v-if="operateFlag !== 'DETAIL'">*</span>输入框类型：
          </div>
          <div v-if="operateFlag == 'DETAIL'">{{ inputTypeOpt[updateForm.inputType] }}</div>
          <el-select v-else v-model="updateForm.inputType" placeholder="请选择输入框类型" style="width: 360px;">
            <el-option v-for="item in enumOpt.inputTypeList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item v-if="['INPUT'].includes(updateForm.enterType)" prop="maxLength">
          <div slot="label" class="normal-label">
            文本字数：
          </div>
          <div v-if="operateFlag == 'DETAIL'">{{ updateForm.maxLength }}</div>
          <el-input v-else v-model="updateForm.maxLength" placeholder="请输入文本字数（默认不限制字数）" style="width: 360px;"></el-input>
        </el-form-item> -->
        <el-form-item v-if="['SELECT', 'RADIO', 'CHECKBOX'].includes(updateForm.enterType)" prop="dictType">
          <div slot="label" class="normal-label">
            <span v-if="operateFlag !== 'DETAIL'">*</span>字典类型
            <el-tooltip effect="dark" placement="top-start" :offset="100">
              <div slot="content" class="update-tooltip">
                注意：字典类型为了匹配对应控件枚举值而设置，请勿随意填写，对应值是字典管理中存在的字典类型！
              </div>
              <i class="el-icon-warning" style="color: red;"></i>
            </el-tooltip>：
          </div>
          <div v-if="operateFlag == 'DETAIL'">{{ updateForm.dictType }}</div>
          <el-input v-else v-model="updateForm.dictType" placeholder="请输入枚举类型" style="width: 360px;"></el-input>
        </el-form-item>
        <el-form-item v-if="['DATE', 'MONTH', 'YEAR', 'DATE_TANGE'].includes(updateForm.enterType)" prop="dateFormate">
          <div slot="label" class="normal-label">
            日期格式
            <el-tooltip effect="dark" placement="top-start" :offset="100">
              <div slot="content" class="update-tooltip">
                注意：日期格式默认为“yyyy-MM-dd”，如果有特殊要求可根据示例自定义【年月日：yyyy-MM-dd；年月：yyyy-MM；月日：MM-dd；年月日时分秒：yyyy-MM-dd hh:mm:ss】。
              </div>
              <i class="el-icon-warning" style="color: red;"></i>
            </el-tooltip>：
          </div>
          <div v-if="operateFlag == 'DETAIL'">{{ updateForm.dateFormate }}</div>
          <el-input v-else v-model="updateForm.dateFormate" placeholder="请输入日期格式" style="width: 360px;"></el-input>
        </el-form-item>
        <el-form-item prop="isReadOnly">
          <div slot="label" class="normal-label">
            <span v-if="operateFlag !== 'DETAIL'">*</span>是否只读：
          </div>
          <div v-if="operateFlag == 'DETAIL'">{{ ['否', '是'][updateForm.isReadOnly] }}</div>
          <el-radio-group v-else v-model="updateForm.isReadOnly">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item prop="fieldSort">
          <div slot="label" class="normal-label">
            <span v-if="operateFlag !== 'DETAIL'">*</span>排序：
          </div>
          <div v-if="operateFlag == 'DETAIL'">{{ updateForm.fieldSort }}</div>
          <el-input-number v-else v-model="updateForm.fieldSort" controls-position="right" :min="0" />
        </el-form-item> -->
        <el-form-item prop="remark">
          <div slot="label" class="normal-label">备注：</div>
          <div v-if="operateFlag == 'DETAIL'">{{ updateForm.remark }}</div>
          <el-input v-else v-model="updateForm.remark" placeholder="请输入备注（最多录入255个字符）" type="textarea" :rows="4" maxlength="255" style="width: 360px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <template v-if="operateFlag == 'DETAIL'">
          <el-button type="primary" @click="updateCancel">关 闭</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="updateSubmit">确 定</el-button>
          <el-button @click="updateCancel">取 消</el-button>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getInfoConfigList, editInfoConfig, deleteInfoConfig, getUnMateList, getMateLevel } from "@/api/system/infoConfig";

export default {
  name: "InfoConfig",
  data() {
    const validateFieldType = (rule, value, callback) => {
      if (['SELECT', 'RADIO', 'CHECKBOX'].includes(this.updateForm.enterType)){
        if (value) {
          callback();
        } else {
          callback(new Error('字典类型不能为空'));
        }
      }
      callback();
    };
    const validateTextCount = (rule, value, callback) => {
      if (value) {
        let reg = /^[0-9]*[1-9][0-9]*$/
        if (!reg.test(value)) {
          callback(new Error('文本字数必须是正整数！'));
        }
      }
      callback();
    };
    return {
      queryForm: {
        fieldName: '',
        fieldCode: '',
        level: '',
        pageNum: 1,
        pageSize: 20,
      },
      formList: [
        {
          label: '信息字段名称',
          value: '',
          prop: 'fieldName',
          type: 'INPUT',
          emunName: ''
        },
        {
          label: '信息字段编码',
          value: '',
          prop: 'fieldCode',
          type: 'INPUT',
          emunName: ''
        },
        {
          label: '客户信息等级',
          value: '',
          prop: 'level',
          type: 'SELECT',
          emunName: 'levelList'
        },
      ],
      enumOpt: {
        levelList: [],
        enterTypeList: [],
        inputTypeList: [
          { dictLabel: '文本', dictValue: 'TEXT' },
          { dictLabel: '数字', dictValue: 'NUMBER' },
          { dictLabel: '手机号码', dictValue: 'PHONE' },
          // { dictLabel: '密码', dictValue: 'PASSWORD' },
        ]
      },
      levelOpt: {},
      enterTypeOpt: {},
      inputTypeOpt: {
        'TEXT': '文本',
        'NUMBER': '数字',
        'PASSWORD': '密码',
        'PHONE': '手机号码'
      },
      loading: false,
      infoList: [],
      total: 0,
      title: '',
      operateFlag: '',
      updateVisible: false,
      updateForm: {
        fieldName: '',
        fieldCode: '',
        level: '',
        inputType: '',
        maxLength: null,
        enterType: '',
        dictType: '',
        dateFormate: '',
        isReadOnly: '0',
        remark: '',
        fieldSort: 0
      },
      fieldCodeList: [],
      updateRules: {
        fieldName: [{ required: true, message: "字段名称不能为空", trigger: "blur" }],
        fieldCode: [{ required: true, message: "字段编码不能为空", trigger: "blur" }],
        level: [{ required: true, message: "客户信息等级不能为空", trigger: "change" }],
        enterType: [{ required: true, message: "控件类型不能为空", trigger: "change" }],
        dictType: [{ validator: validateFieldType, trigger: "blur" }],
        maxLength: [{ validator: validateTextCount, trigger: "blur" }],
      },
      saveLoading: false,
      // 等级授权配置
      configVisible: false,
      configForm: {
        level: '1',
        fieldName:'',
        fieldCode:'',
        fieldCodeList: [],
      },
      configList: [],
      leftData: [],
      rightData: []
    };
  },
  created() {
    this.getEnumList();
  },
  methods: {
    getEnumList() {
      this.getDicts("sys_config_level").then((res) => {
        if (res.code == 200) {
          this.enumOpt.levelList = res.data;
          res.data.forEach(item => {
            this.levelOpt[item.dictValue] = item.dictLabel;
          })
        }
      });
      this.getDicts("sys_config_enter_type").then((res) => {
        if (res.code == 200) {
          this.enumOpt.enterTypeList = res.data;
          res.data.forEach(item => {
            this.enterTypeOpt[item.dictValue] = item.dictLabel;
          })
        }
      });
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryForm.pageNum = 1
      this.getInfoListFn()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.queryForm = {}
      this.getInfoListFn();
    },
    // 翻页
    handleSizeChange(val) {
      this.queryForm.pageNum = 1
      this.queryForm.pageSize = val
      this.getInfoListFn()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.getInfoListFn()
    },
    getInfoListFn() {
      this.loading = true;
      getInfoConfigList(this.queryForm).then(res => {
        if (res.code == 200) {
          this.infoList = res.rows || [];
          this.total = res.total || 0;
        }
        this.loading = false;
      })
    },
    handleLevelConfig() {
      this.configList = [];
      getUnMateList().then(res => {
        if (res.code == 200) {
          res.data && res.data.forEach(item => {
            this.configList.push({
              key: item.fieldCode,
              label: item.fieldName,
              disabled: false,
            })
          })
        }
      });
      this.levelChange()
      this.configVisible = true;
    },
    // 变更等级获取其相关表字段信息
    levelChange() {
      this.configForm.fieldCodeList = [];
      getInfoConfigList({ level: this.configForm.level,fieldCode:'',fieldName:'' }).then(res => {
        if (res.code == 200) {
          res.rows && res.rows.forEach(item => {
            this.configForm.fieldCodeList.push(item.fieldCode);
            this.configList.push({
              key: item.fieldCode,
              label: item.fieldName,
              disabled: false,
            })
          });
        }
      })
    },
    // 穿梭框变更
    handleChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys);
    },
    configSubmit() {
      this.saveLoading = true;
      getMateLevel(this.configForm).then(res => {
        if (res.code == 200) {
          this.$message.success('等级权限配置成功！')
          this.handleQuery()
        }
        this.configVisible = false;
        this.saveLoading = false;
      })
    },
    configCancel() {
      this.configVisible = false;
      this.configForm = {
        level: '1',
        fieldCodeList: [],
      };
    },
    // 详情
    handleFieldDetail(row) {
      this.updateForm = row;
      this.updateVisible = true;
      this.title = '客户信息配置'
      this.operateFlag = 'DETAIL'
    },
    // 修改
    handleEditField(row) {
      this.updateForm = JSON.parse(JSON.stringify(row));
      this.updateVisible = true;
      this.title = '编辑客户信息配置'
      this.operateFlag = 'EDIT'
    },
    enterTypeChange() {
      if (['INPUT'].includes(this.updateForm.enterType)) {
        this.updateForm.inputType = 'TEXT'
      } else {
        this.updateForm.dictType = ''
        this.updateForm.inputType = ''
        this.updateForm.dateFormate = ''
      }
      this.updateForm.maxLength = null
    },
    updateSubmit() {
      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          editInfoConfig(this.updateForm).then(res => {
            if (res.code == 200) {
              this.$message.success('字段信息更新成功！')
              this.handleQuery()
            }
            this.updateVisible = false;
          })
        } else {
          this.$message.error('请将数据填写完整！')
          return
        }
      })
    },
    updateCancel() {
      this.updateVisible = false;
      this.$refs.updateForm.resetFields();
      this.updateForm = {}
    },
    // 删除
    handleDelField(row) {
      this.$confirm("是否确认删除该条字段?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        return deleteInfoConfig(row.fieldId);
      }).then(() => {
        this.handleQuery();
        this.$message.success("删除成功！");
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../../styles/base.scss";
.info-config-container{
}
.update-form{
  .normal-label{
    display: flex;
    align-items: center;
    justify-content: end;
    span{
      color: red;
      margin-right: 4px;
    }
  }
}
.update-tooltip {
  width: 260px;
  background: #303133;
  color: white;
  padding: 10px;
  margin: -11px;
  border-radius: 4px;
  word-break: break-all;
}
.my-transfer-dialog{
  .my-transfer{
    margin: 20px 0 10px 0;
    display: flex;
    align-items: center;
    .transfer-icon{
      width: 4px;
      height: 20px;
      background-color: #082aff;
    }
    .transfer-title{
      font-size: 14px;
      margin-left: 8px;
    }
  }
  .special-tip{
    width: 100%;
    font-size: 14px;
    padding: 6px 10px;
    height: auto;
    margin-bottom: 10px;
  }
  ::v-deep .el-transfer-panel{
    // width: 258px;
    flex: 1
  }
  ::v-deep .el-transfer-panel__item.el-checkbox {
    line-height: normal;
    height: auto;
  }
  ::v-deep .el-transfer-panel__item.el-checkbox .el-checkbox__label{
    overflow: visible;
    white-space: pre-wrap;
    line-height: normal;
    line-height: 30px;
    height: auto;
  }
}
</style>
